package com.hazam.beans;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

import com.hazam.util.L;

import android.text.TextUtils;

public class BeanUtils {

	private static String composeSetterMethodNameForField(String s) {
		return "set" + capitalize(s);
	}

	private static String composeGetterMethodNameForField(String s) {
		return "get" + capitalize(s);
	}
	
	private static String capitalize(String s) {
		if (!TextUtils.isEmpty(s)) {
			return Character.toUpperCase(s.charAt(0)) + s.substring(1);
		} else {
			return s;
		}
	}

	public static void setProperty(Object target, String name, Object value) {
		final Class<?> tclass = target.getClass();
		try {
			Method setter = tclass.getMethod(composeSetterMethodNameForField(name), value.getClass());
			setter.invoke(target, value);
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static Object getProperty(Object target, String name) {
		final Class<?> tclass = target.getClass();
		try {
			Method setter = tclass.getMethod(composeGetterMethodNameForField(name));
			return setter.invoke(target);
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	public static List<String> listProperties(Class<?> t) {
		Field[] ff = t.getDeclaredFields();
		List<String> toret = new ArrayList<String>();
		for (Field f: ff) {
			if (!f.isSynthetic()) {
				toret.add(f.getName());
			}
		}
		return toret;
	}
}
